package com.ias.agdis_r.fragment.box;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;

import com.ias.agdis_r.R;
import com.ias.agdis_r.activity.BaseFragment;
import com.ias.agdis_r.activity.BoxActivity;
import com.ias.agdis_r.activity.task.NFTaskInfoActivity;
import com.ias.agdis_r.activity.task.TaskInfoActivity;
import com.ias.agdis_r.adapter.BoxAdapter;
import com.ias.agdis_r.bean.task.Task;
import com.ias.agdis_r.db.BoxDBHelper;
import com.ias.agdis_r.manager.DataBaseManager;
import com.ias.agdis_r.manager.DataManager;
import com.ias.agdis_r.manager.EffectManager;
import com.ias.agdis_r.manager.JavaBeanManager;
import com.ias.agdis_r.module.MessageModel;
import com.ias.agdis_r.terminalmanager.restful.base.endpoint.response.BaseResponse;
import com.ias.agdis_r.view.boxxlistview.MyListView;
import com.ias.agdis_r.view.boxxlistview.MyListView.IXListViewListener;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 消息盒子_任务页面
 * @author guoxr
 *
 */
public class BoxTabTask extends BaseFragment implements IXListViewListener {
	private MyListView mListView;
	private Handler handler;
	private List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
	private List<Map<String, Object>> otherslist = new ArrayList<Map<String, Object>>();
	private BoxAdapter mAdapter;
	private int loadMore = 0;
	private static final int REQUESTCODE = 1;
	public static final int RESULTCODE = 1;
	private TextView noInfo;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.box_tab_task, container, false);
		handler = new Handler();
		mListView = (MyListView) view.findViewById(R.id.xListView);
		noInfo =(TextView) view.findViewById(R.id.tv_noInfo);
		initData();
		mListView.setPullRefreshEnable(false);
		// 设置回调函数
		mListView.setXListViewListener(this);
		// 设置适配器
		mAdapter = new BoxAdapter(getActivity().getApplicationContext(), list);
		mListView.setAdapter(mAdapter);
		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				String tnb = list.get(position - 1).get("tnb").toString();
				DataManager dataManager = DataManager.getInstance();
				if (dataManager.getWorkTask(tnb) == null
						&& dataManager.getHistoryWorkTask(tnb) == null
						&& dataManager.getReceiveTask(tnb) == null
						&& dataManager.getWorkNFTask(tnb) == null
						&& dataManager.getNFHistoryWorkTask(tnb) == null
						&& dataManager.getReceiveNFTask(tnb) == null) {
					EffectManager.getInstance().ttsPlay(
							EffectManager.TTS_TYPE_TASK, DataBaseManager.getInstance().getContext().getString(R.string.noTask), false);
					isAllCheck(new String[]{tnb, JavaBeanManager.getInstance().getUserinfo().getEnb()});
				} else {
					Task task = dataManager.getWorkTask(tnb);
					if (null == task){
						task = dataManager.getHistoryWorkTask(tnb);
					}
					if (null == task){
						task = dataManager.getReceiveTask(tnb);
					}
					if (null == task){
						task = dataManager.getWorkNFTask(tnb);
					}
					if (null == task){
						task = dataManager.getNFHistoryWorkTask(tnb);
					}
					if (null == task){
						task = dataManager.getReceiveNFTask(tnb);
					}
					if (null != task) {
						if ("Y".equals(task.getEVENT())){
							//删除NFTaskInfoActivity，重新生成实例
							DataBaseManager.getInstance().removeNFTaskInfoActivity();
							Intent intent = new Intent(getActivity(), NFTaskInfoActivity.class);
							intent.putExtra(MessageModel.TNB, tnb);
							//intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
							startActivityForResult(intent, REQUESTCODE);
						}else {
							//删除TaskInfoActivity，重新生成实例
							DataBaseManager.getInstance().removeTaskInfoActivity();
							Intent intent = new Intent(getActivity(), TaskInfoActivity.class);
							intent.putExtra(MessageModel.TNB, tnb);
							//intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
							startActivityForResult(intent, REQUESTCODE);
						}
					}
				}
			}
		});
		return view;
	}
	/**
	 * 标记此tnb下的所有变更消息为已读
	 */
	private void isAllCheck(String[] selectionArgs) {
		// TODO Auto-generated method stub
		BoxDBHelper dbHelper = new BoxDBHelper(DataBaseManager.getInstance()
				.getContext());
		int i = dbHelper.isAllCheck("select count(1) from "
				+ BoxDBHelper.TABLE_TASK
				+ " where ischeck=0 and tnb=? and enb = ?", selectionArgs);
		if (i > 0) {
			dbHelper.setCheck(BoxDBHelper.TABLE_TASK, "tnb = ? and enb = ?",
					selectionArgs);
			DataManager.getInstance().setUnCheckNumber(
					DataManager.getInstance().getUnCheckNumber() - i);
			BoxActivity activity = (BoxActivity) getActivity();
			activity.updateUI(MessageModel.REFRESH);
		}
		dbHelper.closeDB();
	}
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == REQUESTCODE && resultCode == RESULTCODE) {
			BoxActivity activity = (BoxActivity) getActivity();
			activity.updateUI(MessageModel.REFRESH);
		}
	}

	@Override
	public void onRefresh() {
		handler.postDelayed(new Runnable() {
			@Override
			public void run() {
				mListView.stopRefresh();
			}
		}, 1000);
	}

	@Override
	public void onLoadMore() {
		if (otherslist == null) {
			mListView.stopLoadMore();
			return;
		}
		list.addAll(addlist(otherslist));
		mAdapter.notifyDataSetChanged();
		mListView.stopLoadMore();
		if (list.size()==0){
			noInfo.setVisibility(View.VISIBLE);
		}
		loadMore++;
	}

	private List<Map<String, Object>> addlist(List<Map<String, Object>> other) {
		// TODO Auto-generated method stub
		List<Map<String, Object>> mylist = new ArrayList<Map<String, Object>>();
		for (int i = 0; i < BoxActivity.LOARMORE; i++) {
			if (other.size() > 0) {
				mylist.add(other.get(0));
				other.remove(0);
			} else {
				mListView.setPullLoadEnable(false);
				break;
			}
		}
		return mylist;
	}

	private void initData() {
		// TODO Auto-generated method stub
		noInfo.setVisibility(View.GONE);
		mListView.setPullLoadEnable(true);
		if (list != null) {
			list.clear();
		}
		if (BoxActivity.taskNo != null) {
			BoxActivity.taskNo.clear();
		}
		otherslist = DataManager.getInstance().getTaskChangeList();
		if (otherslist == null) {
			return;
		}
		for (int i = 0; i < otherslist.size(); i++) {
			if (otherslist.get(i).get("ischeck").equals("0")) {
				list.add(otherslist.get(i));
				BoxActivity.taskNo.add(new String[] { (String) otherslist
						.get(i).get("_id") });
				otherslist.remove(i);
				i--;
			}
		}
	}

	@Override
	protected void operateResponseSucess(String serviceId, BaseResponse response) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void updateUI(String tag) {
		// TODO Auto-generated method stub
		if (tag.equals("BoxTabTask")) {
			initData();
			mAdapter.notifyDataSetChanged();
			// int load = loadMore;
			// for (int i = 0; i < load; i++) {
			// onLoadMore();
			// }
			// loadMore = load;
		}
	}
}
